package com.jhaosdk;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.Settings;
import android.util.Log;

import org.cocos2dx.lib.Cocos2dxHelper;
import org.cocos2dx.lib.Cocos2dxJavascriptJavaBridge;
import org.json.JSONObject;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class NativeSdkHelper {

    private static final String TAG = "NativeSdkHelper";

    private static String[] PERMISSIONS_STORAGE = {
            "android.permission.WRITE_EXTERNAL_STORAGE",
            "android.permission.READ_EXTERNAL_STORAGE"
    };


    public static String mImagePath = "";

    /**
     * 获取android唯一id
     * @return
     */
    public static String getUDID(){
        String ANDROID_ID =  Settings.Secure.getString(Cocos2dxHelper.getActivity().getContentResolver(), Settings.Secure.ANDROID_ID);
        Log.i(TAG,"NativeSdkHelper=getUDID"+ ANDROID_ID);
        return ANDROID_ID;
    }

    public  static String getLocation(){
        Log.i(TAG,  "getAddress=");

        Cocos2dxHelper.getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                LocationUtils.getInstance(Cocos2dxHelper.getActivity()).getLocation();
            }
        });
        return  "";
    }

    public  static  void selectPhoto(String info){
        try{
            JSONObject jsonObject = new JSONObject(info);
            final Integer clipX = jsonObject.getInt("clipX");
            final Integer clipY = jsonObject.getInt("clipY");
            mImagePath = jsonObject.getString("tmpPath");
            Cocos2dxHelper.getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
//                    PicCrop.CropConfig config = new PicCrop.CropConfig();
//                    config.maxWidth = clipX;
//                    config.maxHeight = clipY;
//                    PicCrop.cropAvatarFromGallery(Cocos2dxHelper.getActivity(), config);
                }
            });
        }catch(Exception e){
            e.printStackTrace();
            Log.i(TAG,"selectPhoto --------error-------" + e.getMessage());
        }

    }

    public  static  void savePic(Uri uri){
        Log.i(TAG,"savePic -------------" );
//        FileProvider7.getFilePathString(Cocos2dxHelper.getActivity(), uri, mImagePath);
        callbackToNativeSdkHelper("onSelectPhoto_callback", mImagePath);
    }


    public static void saveToNativeAlbum(String picPath){
        Log.i("saveToNativeAlbum", picPath);
        if (Build.VERSION.SDK_INT >= 23)
        {
            List<String> permissionList = new ArrayList<>();

            // 遍历每一个申请的权限，把没有通过的权限放在集合中
            for (String permission : PERMISSIONS_STORAGE) {
                if (Cocos2dxHelper.getActivity().checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) {
                    permissionList.add(permission);
                }
            }
            // 申请权限
            if (!permissionList.isEmpty()) {
                Cocos2dxHelper.getActivity().requestPermissions(permissionList.toArray(new String[permissionList.size()]), 0);
                return;
            }
        }
        NativeSdkHelper.saveToNativeAlbumSure(picPath);
    }

    public static void saveToNativeAlbumSure(String picPath){
        Log.i("saveToNativeAlbumSure", picPath);
        try {
            FileInputStream fis = new FileInputStream(picPath);
            Bitmap bitmap  = BitmapFactory.decodeStream(fis);
            String[] picArr = picPath.split("/");
            String picName = picArr[picArr.length-1];
            Log.i("picName==",picName);
            NativeSdkHelper.saveBmp2Gallery(bitmap, picName);
        }catch (FileNotFoundException ex){
            Log.e("FileNotFoundException==",ex.getMessage());
//            ((Cocos2dxActivity)(NativeBridge.nowActivity)).runOnGLThread(new Runnable() {
//                @Override
//                public void run() {
//                    String tempdd = "JsNativeBridge.saveToNativeAlbumResp('保存失败')";
//                    Cocos2dxJavascriptJavaBridge.evalString(tempdd);
//                }
//            });
        }
    }


    /**
     * @param bmp 获取的bitmap数据
     * @param picName 自定义的图片名
     */
    public static void saveBmp2Gallery(Bitmap bmp, String picName) {
        String fileName = null;
        //系统相册目录
        String galleryPath= Environment.getExternalStorageDirectory()
                + File.separator + Environment.DIRECTORY_DCIM
                +File.separator+"Camera"+File.separator;
        // 声明文件对象
        File file = null;
        // 声明输出流
        FileOutputStream outStream = null;

        try {
            // 如果有目标文件，直接获得文件对象，否则创建一个以filename为名称的文件
            file = new File(galleryPath, picName);

            // 获得文件相对路径
            fileName = file.toString();
            // 获得输出流，如果文件中有内容，追加内容
            outStream = new FileOutputStream(fileName);
            if (null != outStream) {
                bmp.compress(Bitmap.CompressFormat.JPEG, 90, outStream);
            }
        } catch (Exception e) {
            e.getStackTrace();
        }finally {
            try {
                if (outStream != null) {
                    outStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        MediaStore.Images.Media.insertImage(Cocos2dxHelper.getActivity().getContentResolver(),bmp,fileName,null);
        Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        Uri uri = Uri.fromFile(file);
        intent.setData(uri);
        Cocos2dxHelper.getActivity().sendBroadcast(intent);
    }


    public static void callbackToNativeSdkHelper(final String function, final String result) {
        Cocos2dxHelper.runOnGLThread(new Runnable() {
            @Override
            public void run() {
                Log.i("callbackNativeSdkHelper", "function="+function+" result="+ result);
                Cocos2dxJavascriptJavaBridge.evalString("NativeSdkHelper." + function + "('" + result + "')");
            }
        });
    }

}
